
import { calc , type PinConfig } from "./gpio";
import { Reg } from "../reg";

class SourceCode {

    name: string;
    src: string;

    constructor(name: string) {
        this.name = name;
        this.src = '';
    }

    append(line: string) {
        if (line.length != 0) {
            this.src += '\t';
            this.src += line;
            this.src += '\r\n';
        }
        return this;
    }

    nextLine() {
        this.src += '\r\n';
        return this;
    }

    create() {
        let s = `void ${this.name}() {`;
        s += this.src;
        s += `}\r\n`;
        return s;
    }
}


export function create(name: string, pinCfg: PinConfig[]) {
    const cfgs = calc(pinCfg);
    const sc = new SourceCode(name);
    for (const cfg of cfgs) {
        sc.nextLine();

        const crl = new Reg(`${cfg.port}->CRL`, 32);
        const crh = new Reg(`${cfg.port}->CRH`, 32);
        const brr = new Reg(`${cfg.port}->BRR`, 16);
        const bsrr = new Reg(`${cfg.port}->BSRR`, 16);

        sc.append( crl.modify(cfg.crl_mask, cfg.crl) );
        sc.append( crh.modify(cfg.crh_mask, cfg.crh) );
        sc.append( brr.write1(cfg.brr) );
        sc.append( bsrr.write1(cfg.bsrr) );
    }
    return sc.create();
}



